<?php

namespace app\controller;

use app\BaseController;
use app\common\Pay;
use app\common\Sms;
use app\common\TencentIm;
use app\common\UsersService;
use app\model\Activity;
use app\model\Config;
use app\model\Forum;
use app\model\Friends;
use app\model\FriendsUsers;
use app\model\Point;
use app\model\Question;
use app\model\QuestionAnswer;
use app\model\Recruit;
use app\model\Room;
use app\model\SecGoods;
use app\model\StoreAssess;
use app\model\Talent;
use app\model\TalentDocument;
use app\model\Users;
use app\model\UsersAd;
use app\model\UsersAlbum;
use app\model\UsersCollect;
use app\model\UsersFollow;
use app\model\UsersFootmark;
use app\model\UsersOrder;
use app\model\UsersScoreLog;
use app\model\Vip;
use app\Request;
use app\tool\Http;
use app\tool\TLSSigAPIV2;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\Exception;
use think\response\Json;

class UsersController extends BaseController
{
	
	protected array $middleware = ['Login' => [
		'except' => ['test', 'users_info', 'my_save', 'check_follow', 'get_vip'],
	]];
	
	
	/**
	 * @title 会员支付
	 * @param Request $request
	 * @return Json
	 */
	function vip_pay(Request $request): Json
	{
		$pay_type = $request->post('pay_type/d');
		$id = $request->post('id/d');

		$vip = Vip::find($id);
		if (!$vip) {
			writeJson(0, '会员价格获取失败');
		}
		$order_sn = get_uniqid();
		$data = [
			'users_id' => $request->users_id,
			'type' => 'vip',
			'order_sn' => $order_sn,
			'amount' => $vip->price,
			'pay_type' => $pay_type,
			'pro_id' => $vip->id,
		];
		$res=UsersOrder::create($data);
		if ($pay_type==3){
			$res = ['apple'=>$vip->ios,'order_sn'=>$res->order_sn,'attach'=>'vip_pay'];
		}else{
			try {
				$res = Pay::pay($pay_type, $vip->price, $order_sn, 'Vip充值', 'vip_pay');
			} catch (Exception $e) {
				writeJson(0, $e->getMessage());
			}
		}
		
		writeJson(1,'',$res);
	}
	
	
	/**
	 * @title 充值积分支付
	 * @param Request $request
	 * @return Json
	 */
	function point_pay(Request $request): Json
	{
		$id = $request->post('id/d'); // id  pay_type 1微信  2支付宝
		$pay_type = $request->post('pay_type/d');
		$point = Point::find($id);
		if (!$point) {
			writeJson(0, '积分价格获取失败');
		}
		$order_sn = get_uniqid();
		$data = [
			'users_id' => $request->users_id,
			'type' => 'point',
			'order_sn' => $order_sn,
			'amount' => $point['price'],
			'pay_type' => $pay_type,
			'pro_id' => $point->id
		];
		UsersOrder::create($data);
		if ($pay_type==3){
			$res = ['apple'=>$point->ios,'order_sn'=>$order_sn,'attach'=>'point_pay'];
		}else{
			try {
				$res = Pay::pay($pay_type, $point['price'], $order_sn, '积分充值', 'point_pay');
			} catch (Exception $e) {
				writeJson(0, $e->getMessage());
			}
		}
		
		writeJson($res);
	}
	
	/**
	 * 获取积分价格表
	 * @return Json
	 */
	function get_point()
	{
		$rows = Point::order(['weigh' => 'desc'])->select();
		
		writeJson($rows);
	}
	
	/**
	 * 获取会员价格表
	 * @return Json
	 */
	function get_vip()
	{
		$res = Vip::order(['weigh'=>'desc'])->select();
		writeJson($res);
	}
	
	/**
	 * 我的活动
	 * @param Request $request
	 * @param int $type
	 * @return Json
	 */
	function my_play(Request $request, int $type)
	{
		$res = FriendsUsers::with(['friends'])
			->hasWhere('friends')
			->when(in_array($type, [2, 3, 4]), function (Query $query) use ($type) {
				switch ($type) {
					case 2:
						$query->whereBetweenTimeField('Friends.start_time', 'end_time');
						break;
					case 3:
						$query->whereBetweenTimeField('Friends.play_start_time', 'play_end_time');
						break;
					case 4:
						$query->whereTime('Friends.play_end_time', '<=', time());
						break;
				}
			})
			->order('id', 'desc')
			->where('FriendsUsers.users_id', $request->users_id)
			->paginate()
			->items();
		writeJson($res);
	}
	
	
	/**
	 * 他人主页
	 * @param int $users_id
	 * @return Json
	 */
	function users_info(int $users_id)
	{
		$users = Users::withCount('follow')
			->withCount('fans')
			->find($users_id);
		
		$album = UsersAlbum::where(['users_id' => $users_id])->order(['weigh' => 'desc'])->limit(10)->select();
		writeJson(['users' => $users, 'album' => $album]);
	}
	
	/**
	 * 我的-编辑
	 * @param Request $request
	 * @return Json
	 * @throws DbException
	 * @throws Exception
	 */
	function users_edit(Request $request)
	{
		
		$row = Users::find($request->users_id);
		if (!$row){
			writeJson(100, '重新登陆');
		}
		if (false === $request->isPost()) {
			$collect = UsersCollect::where('users_id', $request->users_id)->count(); // 收藏
			$guanzhu = UsersFollow::where('users_id', $request->users_id)->count(); //关注
			$fans = UsersFollow::where('to_users_id', $request->users_id)->count(); //粉丝
			$zuji = UsersFootmark::where(['users_id' => $request->users_id])->count();//足迹
			$ad = UsersAd::where(['users_id' => $request->users_id])->whereTime('createtime','today')->count();//今天次数
			$row->collect = $collect;
			$row->zuji = $zuji;
			$row->guanzhu = $guanzhu;
			$row['fans'] = $fans;
			$row->ad = GptController::$ad - $ad;
			writeJson($row);
		}
		$params = $request->post();
		if (empty($params)) {
			throw new Exception('参数错误');
		}
		if (array_key_exists('createtime',$params)){
			unset($params['createtime']);
		}
		$TencentIm = TencentIm::getInstance();
		if (isset($params['head_image'])) {
			$TencentIm->portrait_set($request->users_id, [['Tag' => 'Tag_Profile_IM_Image', 'Value' => config('app.static_host') . $params['head_image']]]);
		}
		if (isset($params['nickname'])) {
			$TencentIm->portrait_set($request->users_id, [['Tag' => 'Tag_Profile_IM_Nick', 'Value' => $params['nickname']]]);
		}
		$result = $row->save($params);
		if (false === $result) {
			throw new Exception('无更新');
		}
		
		writeJson();
		
	}
	
	/**
	 * 我的
	 * 收藏 / 足迹
	 * @param Request $request
	 * @param int $type
	 * @param int $sec_type
	 * @param int $of
	 * @return Json
	 */
	function my_collect(Request $request, int $type, mixed $sec_type, int $of)  //of = 1收藏 2足迹
	{
		//类型:1=互动问答,2=我的房屋,3=我的闲置,4=论坛,5=引进计划,6=活动交友,7=求职招聘,8=商家点评,9=我的爆料,10=新闻
		if ($of == 1) {
			$model = UsersCollect::order(['id' => 'desc']);
		} else {
			$model = UsersFootmark::order(['updatetime' => 'desc']);
		}
		$model_name = $model->getName();
		switch ($type) {
			
			case 1:
				$res = $model
					->filter(function ($data) {
						if ($data->type == 'question_answer') {
							$data->info = QuestionAnswer::with(['question' => function (Query $query) {
								$query->removeOption('soft_delete');
							}])->where(['id' => $data->pro_id])->find();
						} else {
							$data->info = Question::withTrashed()->where(['id' => $data->pro_id])->find();
						}
					})
					->where(['users_id' => $request->users_id])
					->whereIn('type', ['question', 'question_answer']);
				break;
			case 2:
				$res = $model
					->hasWhere('room', function (Query $query) use ($sec_type) {
						$query->where(['type' => $sec_type]);
					})
					->with(['room' => function (Query $query) {
						$query->with(['users']);
					}])
					->where([$model_name . '.users_id' => $request->users_id, $model_name . '.type' => 'room']);
				break;
			case 3:
				$res = $model
					->with(['secgoods' => function (Query $query) {
						$query->with(['users']);
					}])
					->where(['users_id' => $request->users_id, 'type' => 'secgoods']);
				break;
			case 4:
				$res = $model
					->with(['forum' => function (Query $query) {
						$query->with(['users']);
					}])
					->where(['users_id' => $request->users_id, 'type' => 'forum']);
				break;
			
			case 5:
				$res = $model
					->hasWhere('talent', function (Query $query) use ($sec_type) {
						$query->where(['type' => $sec_type]);
					})
					->with(['talent' => function (Query $query) {
						$query->with(['users']);
					}])
					->where([$model_name . '.users_id' => $request->users_id, $model_name . '.type' => 'talent']);
				break;
			case 6:
				$res = $model
					->hasWhere('friends', function (Query $query) use ($sec_type) {
						$query->where(['type' => $sec_type]);
					})
					->with(['friends' => function (Query $query) {
						$query->with(['users', 'tags']);
					}])
					->where([$model_name . '.users_id' => $request->users_id, $model_name . '.type' => 'friends']);
				break;
			case 7:
				$res = $model
					->hasWhere('recruit', function (Query $query) use ($sec_type) {
						$query->where(['type' => $sec_type]);
					})
					->with(['recruit' => function (Query $query) {
						$query->with(['users']);
					}])
					->where([$model_name . '.users_id' => $request->users_id, $model_name . '.type' => 'recruit']);
				break;
			case 8:
				$res = $model
					->with(['store_assess' => function (Query $query) {
						$query->with(['users', 'store']);
					}])
					->where(['users_id' => $request->users_id, 'type' => 'store_assess']);
				break;
			case 9:
				$res = $model
					->hasWhere('activity', function (Query $query) use ($sec_type) {
						$query->where(['type' => $sec_type]);
					})
					->with(['activity' => function (Query $query) {
						$query->with(['users']);
					}])
					->where([$model_name . '.users_id' => $request->users_id, $model_name . '.type' => 'activity']);
				break;
			case 10:
				$res = $model
					->with(['news' => function (Query $query) {
						$query->with(['issuer']);
					}])
					->where(['users_id' => $request->users_id, 'type' => 'news']);
				break;
			default:
				writeJson(0, '参数错误');
		}
		$res = $res->paginate()->items();
		writeJson($res);
	}
	
	/**
	 * 我的发布
	 * @param int $user_id
	 * @param int $type
	 * @param int $sec_type
	 * @return Json
	 */
	function my_save(int $user_id, int $type, mixed $sec_type)
	{
		//类型:1=互动问答,2=我的房屋,3=我的闲置,4=论坛,5=引进计划,6=活动交友,7=求职招聘,8=商家点评,9=我的爆料,10=新闻
		// $sec_type
		switch ($type) {
			case 1:
				$res = Question::with(['users'])->where(['users_id' => $user_id])->order('id', 'desc');
				break;
			case 2:
				$res = Room::with(['users'])->where(['users_id' => $user_id, 'type' => $sec_type])->order('id', 'desc');
				break;
			case 3:
				$res = SecGoods::with(['users'])->where(['users_id' => $user_id])->order('id', 'desc');
				break;
			case 4:
				$res = Forum::with(['users'])->where(['users_id' => $user_id])->order('id', 'desc');
				break;
			case 5:
				$res = Talent::with(['users'])->where(['users_id' => $user_id, 'type' => $sec_type])->order('id', 'desc');
				break;
			case 6:
				$res = Friends::with(['users', 'tags'])->where(['users_id' => $user_id, 'type' => $sec_type])->order('id', 'desc');
				break;
			case 7:
				$res = Recruit::with(['users'])->where(['users_id' => $user_id, 'type' => $sec_type])->order('id', 'desc');
				break;
			case 8:
				$res = StoreAssess::with(['users', 'store'])->where(['users_id' => $user_id])->order('id', 'desc');
				break;
			case 9:
				$res = Activity::with(['users'])->where(['users_id' => $user_id, 'type' => $sec_type])->order('id', 'desc');
				break;
			default:
				writeJson(0, '类型错误');
		}
		$rows = $res->paginate()->items();
		writeJson($rows);
	}
	
	/**
	 * 关注
	 * @param Request $request
	 * @return Json
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	function follow(Request $request)
	{
		$id = $request->post('id/d');
		UsersService::follow($id, $request->users_id);
		$row = Users::filter(function ($data) use ($request) {
			$follow = UsersFollow::where(['users_id' => $request->users_id, 'to_users_id' => $data->id])->find();
			$fans = UsersFollow::where(['users_id' => $data->id, 'to_users_id' => $request->users_id])->find();
			if ($follow && $fans) {
				$data->is_friend = 1;
			}
			if (!$follow && !$fans) {
				$data->is_friend = 0;
			}
			if (!$follow && $fans) {
				$data->is_friend = 2;
			}
			if ($follow && !$fans) {
				$data->is_friend = 3;
			}
		})->find($id);
		writeJson($row);
	}
	
	/**
	 * 是否关注
	 * @param Request $request
	 * @return Json
	 */
	function check_follow(Request $request)
	{
		$id = $request->post('id');
		$res = UsersFollow::where(['users_id' => $request->users_id, 'to_users_id' => $id])->find();
		$row = (bool)$res;
		writeJson($row);
	}
	
	/**
	 * 是否收藏
	 * @param Request $request
	 * @return Json
	 */
	function check_collect(Request $request) // type 类型:   question=互动问答,news=新闻,room=房屋租赁,secgoods=二手物品
	{
		$id = $request->post('id');
		$type = $request->post('type');
		$res = UsersCollect::where(['users_id' => $request->users_id, 'type' => $type, 'pro_id' => $id])->find();
		$res ? $res = true : $res = false;
		writeJson($res);
	}
	
	
	/**
	 * 获取腾讯ImSign
	 * @return Json
	 * @throws \Exception
	 */
	function get_im_sign(Request $request)
	{
		$identifier = $request->users_id;
		$row = Config::getFieldByName('tencent_cloud', 'value');
		$row = json_decode($row);
		$tls = new TLSSigAPIV2($row->imAppid, $row->imKey);
		$res = $tls->genUserSig($identifier);
		writeJson($res);
	}
	
	/**
	 * 好友列表
	 * @param Request $request
	 * @param int $type
	 * @param int $online
	 * @return Json
	 * @throws DataNotFoundException
	 * @throws DbException
	 * @throws ModelNotFoundException
	 */
	function friend_list(Request $request, int $type, int $online, string $keyword) //type 1=好友 ，2=关注 , 3 =粉丝
	{
		switch ($type) {
			case 1:
				$fans = UsersFollow::where(['to_users_id' => $request->users_id])->column('users_id');
				$follow = UsersFollow::where(['users_id' => $request->users_id])->column('to_users_id');
				$arr = array_values(array_intersect($fans, $follow));
				$rows = Users::whereIn('id', $arr)
					->filter(function ($data) use ($request) {
//                        $row = UsersFollow::where(['users_id' => $data->id, 'to_users_id' => $request->users_id])->find();
//                        $data->followtime = $row->createtime;
						$data->is_friend = 1;
					})
					->when(!empty($keyword), function (Query $query) use ($keyword) {
						$query->where(['nickname|id' => $keyword]);
					})
					->when(in_array($online, [0, 1]), function (Query $query) use ($online) {
						$query->where(['online' => $online]);
					})
					->order(['id' => 'desc'])
					->paginate();
				break;
			case 2:
				$ids = UsersFollow::where(['to_users_id' => $request->users_id])->field('users_id')->buildSql();//关注我的人
				$rows = Users::field("IF(Users.id in ($ids),1,3) AS is_friend")
					->hasWhere('follow', ['users_id' => $request->users_id])
//                    ->filter(function ($data) use ($request) {
//                        $row = UsersFollow::where(['users_id' => $request->users_id, 'to_users_id' => $data->id])->find();
//                        $data->followtime = $row->createtime;
//                    })
					->when(!empty($keyword), function (Query $query) use ($keyword) {
						$query->where(['nickname|Users.id' => $keyword]);
					})
					->when(in_array($online, [0, 1]), function (Query $query) use ($online) {
						$query->where(['online' => $online]);
					})
					->order(['is_friend' => 'asc', 'Users.id' => 'desc'])
					->paginate();
				break;
			case 3:
				$ids = UsersFollow::where(['users_id' => $request->users_id])->field('to_users_id')->buildSql();//我关注的人
				$rows = Users::field("IF(Users.id in ($ids),1,2) AS is_friend")
					->hasWhere('fans', ['to_users_id' => $request->users_id])
//                    ->filter(function ($data) use ($request) {
//                        $row = UsersFollow::where(['users_id' => $data->id, 'to_users_id' => $request->users_id])->find();
//                        $data->followtime = $row->createtime;
//                    })
					->when(!empty($keyword), function (Query $query) use ($keyword) {
						$query->where(['nickname|Users.id' => $keyword]);
					})
					->when(in_array($online, [0, 1]), function (Query $query) use ($online) {
						$query->where(['online' => $online]);
					})
					->order(['is_friend' => 'asc', 'Users.id' => 'desc'])
					->paginate();
				break;
			default:
				writeJson(0, '参数错误');
			
		}
		writeJson(['count' => $rows->total(), 'list' => $rows->items()]);
	}
	
	
	/**
	 * 好友搜索
	 * @param string $keyword
	 * @param Request $request
	 * @return Json
	 */
	function friend_search(string $keyword, Request $request)
	{
		$rows = Users::where([['nickname|id', 'like', '%' . $keyword . '%'], ['id', '<>', $request->users_id]])->filter(function ($data) use ($request) {
			$follow = UsersFollow::where(['users_id' => $request->users_id, 'to_users_id' => $data->id])->find();
			$fans = UsersFollow::where(['users_id' => $data->id, 'to_users_id' => $request->users_id])->find();
			if ($follow && $fans) {
				$data->is_friend = 1;
			}
			if (!$follow && !$fans) {
				$data->is_friend = 0;
			}
			if (!$follow && $fans) {
				$data->is_friend = 2;
			}
			if ($follow && !$fans) {
				$data->is_friend = 3;
			}
		})->order(['id' => 'desc'])->paginate()->items();
		writeJson($rows);
	}
	
	/**
	 * 添加好友 --------------------- 弃用
	 * @param Request $request
	 * @return Json
	 */
	function friend_add(Request $request)
	{
		$to_users_id = $request->param('to_users_id');
		$follow = UsersFollow::where(['users_id' => $request->users_id, 'to_users_id' => $to_users_id])->find();
		if (!$follow) {
			UsersFollow::create(['users_id' => $request->users_id, 'to_users_id' => $to_users_id]);
		}
		writeJson();
	}
	
	/**
	 * 我的文档
	 * @param Request $request
	 * @param int $type
	 * @return Json
	 */
	function my_document(Request $request, int $type)
	{
		$app_host = config('app.app_host');
		$rows = TalentDocument::where(['users_id' => $request->users_id, 'type' => $type])
			->filter(function ($data)use ($app_host) {
				$data->link = $app_host . $data->link;
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 相册列表
	 * @param Request $request
	 * @return Json
	 */
	function album(Request $request)
	{
		$rows = UsersAlbum::where(['users_id' => $request->users_id])->order(['weigh' => 'desc'])->paginate()->items();
		writeJson($rows);
	}
	
	/**
	 * 删除相册
	 * @param Request $request
	 * @return Json
	 */
	function album_delete(Request $request)
	{
		$id = $request->post('id');
		UsersAlbum::destroy($id);
		writeJson();
	}
	
	/**
	 * 添加相册
	 * @param Request $request
	 * @return Json
	 */
	function album_add(Request $request)
	{
		$image = $request->post('image');
		$res = UsersAlbum::create(['users_id' => $request->users_id, 'image' => $image]);
		writeJson($res);
	}
	
	/**
	 * 相册更换权重
	 * @param Request $request
	 * @return Json
	 */
	function album_weigh(Request $request)
	{
		$ids = $request->post('ids');
		$ids_arr = explode(',', $ids);
		$old = UsersAlbum::where(['users_id' => $request->users_id])->whereIn('id', $ids_arr)->order(['weigh' => 'desc'])->column('weigh');
		foreach ($ids_arr as $k => $v) {
			UsersAlbum::where(['id' => $v])->update(['weigh' => $old[$k]]);
		}
		writeJson();
	}
	
	/**
	 * 积分明细
	 * @param Request $request
	 * @param int $type
	 * @return Json
	 */
	function score_log(Request $request, int $type)
	{
		$rows = UsersScoreLog::where(['users_id' => $request->users_id])
			->when(!empty($type), function (Query $query) use ($type) {
				if ($type == 1) {
					$query->where('score', '>=', 0);
				}
				if ($type == 2) {
					$query->where('score', '<=', 0);
				}
			})
			->filter(function ($data) {
				if ($data->score >= 0) {
					$data->score = '+' . $data->score;
				}
			})
			->order(['id' => 'desc'])
			->paginate()
			->items();
		writeJson($rows);
	}
	
	/**
	 * 绑定微信
	 * @param Request $request
	 * @return void
	 */
	function bind_wechat(Request $request)
	{
		$wx_code = $request->post('wx_code');
		$res = Http::get('https://api.weixin.qq.com/sns/oauth2/access_token', [
			'appid' => 'wxcb3a0e9976ee4226',
			'secret' => 'feb8290893b72da6f005f50d7f9c6f3e',
			'code' => $wx_code,
			'grant_type' => 'authorization_code'
		]);
		$json_obj = json_decode($res);
		if (empty($json_obj->openid)) {
			writeJson(0, $json_obj->errmsg);
		}
		$users = Users::where('wechat_openid', $json_obj->openid)->find();
		if ($users) {
			writeJson(0, '此微信已被绑定');
		}
		$users = Users::find($request->users_id);
		$users->wechat_openid = $json_obj->openid;
		$users->save();
		writeJson();
	}
	
	/**
	 * 绑定QQ
	 * @param Request $request
	 * @return void
	 */
	function bind_qq(Request $request)
	{
		$qq_code = $request->post('qq_code');
		$users = Users::where('qq_openid', $qq_code)->find();
		if ($users) {
			writeJson(0, '此QQ已被绑定');
		}
		$users = Users::find($request->users_id);
		$users->qq_openid = $qq_code;
		$users->save();
		writeJson();
	}
	
	
	
	/**
	 * 更换手机号
	 * @param Request $request
	 * @return void
	 */
	function change_mobile(Request $request)
	{
		$mobile = $request->post('mobile');
		$captcha = $request->post('captcha');
		$code = $request->post('code');
		$row = Users::find($request->users_id);
		$ret = Sms::check($mobile, $captcha, 'changemobile');
		if (!$ret) {
			writeJson(0, '验证码不正确');
		}
		$row->mobile = $mobile;
		$row->code = $code;
		$row->save();
		writeJson();
	}
	
	/**
	 * 账号注销
	 * @param Request $request
	 * @return void
	 */
	function account_off(Request $request)
	{
		$row = Users::find($request->users_id);
		$row->delete();
		writeJson();
	}
	
	
}